package com.lagou.task.servlet;

import com.lagou.task.entity.Student;
import com.lagou.task.service.StudentService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "StudentListServlet",urlPatterns = "/list")
public class StudentListServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        StudentService studentService = new StudentService();
        List<Student> students = studentService.showAllService();
        String p = request.getParameter("page");
        int page;
        try {
            // 当前页
            page = Integer.parseInt(p);
        }catch (NumberFormatException e){
            page = 1;
        }

        // 学生总数
        int totalStudents = students.size();
        // 每页学生数
        int studentPerPage = 5;
        // 总页数
        int totalPages = totalStudents % studentPerPage == 0? totalStudents / studentPerPage:(totalStudents / studentPerPage + 1);
        // 本页起始学生序号
        int beginIndex = (page - 1) * studentPerPage;
        // 本页末尾学生序号
        int endIndex = beginIndex + studentPerPage;
        if (endIndex > totalStudents)
            endIndex = totalStudents;

        // 设置参数
        request.setAttribute("totalStudents",totalStudents);
        request.setAttribute("studentPerPage",studentPerPage);
        request.setAttribute("totalPages",totalPages);
        request.setAttribute("beginIndex",beginIndex);
        request.setAttribute("endIndex",endIndex);
        request.setAttribute("page",page);
        request.setAttribute("students",students);
        request.getRequestDispatcher("list.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
